package cn.abdl.springsecurity.security;

import cn.abdl.springsecurity.config.SecurityProperties;
import cn.abdl.springsecurity.service.CustomUserDetailService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private CustomUserDetailService userDetailService;
    @Autowired
    private CustomLoginSuccessHandler loginSuccessHandler;
    @Autowired
    private CustomAuthenticationEntryPoint entryPoint;
    @Autowired
    private CustomAccessFailedHandler failedHandler;

    @Autowired
    private CustomAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private CustomLogoutHandler customLogoutHandler;
    @Autowired
    private CustomLogoutSuccessHandler customLogoutSuccessHandler;
    @Autowired
    private CustomSessionExpiredHandler sessionExpiredHandler;



    /**
     * 用于统计用户在线
     */
    @Autowired
    private SessionRegistry sessionRegistry;



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] anonResourceUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(securityProperties.getAnonResourceUrl(),",");
        http.authorizeRequests()
                .antMatchers(anonResourceUrl).permitAll()
                // 其他的需要登录后才能访问
                .anyRequest().authenticated()
                .and()
                // 验证码验证类
                .httpBasic()
                .authenticationEntryPoint(entryPoint)
                .and()
                .formLogin()
                // 登录页面
                .loginPage("/login")
                // 登录接口
                .loginProcessingUrl("/doLogin")
                // 配置登录成功自定义处理类
                .successHandler(loginSuccessHandler)
                // 配置登录失败自定义处理类
                .failureHandler(failedHandler)
                .and()
                .logout()
                .addLogoutHandler(customLogoutHandler)
                // 退出登录删除 cookie缓存
                .deleteCookies("JSESSIONID")
                // 配置用户登出自定义处理类
                .logoutSuccessHandler(customLogoutSuccessHandler)
                .and()
                .exceptionHandling()
                // 配置没有权限自定义处理类
                .accessDeniedHandler(accessDeniedHandler)
                .and()
                .sessionManagement()
                .sessionFixation()
                .migrateSession()
                // 在需要使用到session时才创建session
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                // 同时登陆多个只保留一个
                .maximumSessions(1)
                .maxSessionsPreventsLogin(false)
                // 踢出用户操作
                .expiredSessionStrategy(sessionExpiredHandler)
                // 用于统计在线
                .sessionRegistry(sessionRegistry);

        // 取消跨站请求伪造防护
        http.csrf().disable();
        // 防止iframe 造成跨域
        http.headers().frameOptions().disable();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }

}
